﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
using System.IO;
using UnityEngine.UI;

namespace Tutorial
{
    public class CSCallLua : MonoBehaviour
    {
        public Text m_text;
        private AndroidJavaObject m_javaObject;

        LuaEnv luaenv = null;
        public class DClass
        {
            public int f1;
            public int f2;
        }

        [CSharpCallLua]
        public delegate int FDelegate(int a, string b, out DClass c, ref int x, ref string y);

        void Start()
        {
            m_javaObject = new AndroidJavaObject("com.cf.perfectsdk.MainActivity");
            luaenv = new LuaEnv();
            luaenv.AddLoader(SelfDefineLoader);
            luaenv.DoString("require 'hello'");
        }

        /// <summary>
        /// 自定义的路径的加载器
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public byte[] SelfDefineLoader(ref string filepath)
        {
            filepath = filepath.Replace('.', '/');
            filepath = Application.persistentDataPath + "/lua/" + filepath + ".lua.txt";
            Debug.Log(filepath);
            if (File.Exists(filepath))
            {
                return File.ReadAllBytes(filepath);
            }
            else
            {
                return null;
            }
        }

        void OnDestroy()
        {
            luaenv.Dispose();
        }

        public void DoFile(string lua, LuaTable env = null)
        {
            string path = Application.streamingAssetsPath + "/lua/" + lua + ".lua.txt";
            var txt = File.ReadAllText(path);
            luaenv.DoString(txt, lua, env);
        }

        public void Add()
        {
            int add = m_javaObject.Call<int>("add", 1, 2);
            m_text.text = "add=" + add;
        }

        public void SayHello()
        {
            //string str = m_javaObject.Call<string>("Unzip");
            //m_text.text = str;
            AndroidJavaObject androidObject = new AndroidJavaObject("com.cf.perfectsdk.api");
            AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
            if (activity == null)
                return;
            string str = androidObject.Call<string>("Unzip", activity);
            m_text.text = str;
        }

        public void CopyFile()
        {
            AndroidJavaObject androidObject = new AndroidJavaObject("com.cf.perfectsdk.api");
            AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
            if (activity == null)
                return;
            androidObject.Call("copyDir", activity, "lua", Application.persistentDataPath);
        }
    }
}